package com.jkl.service.drTable;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jkl.comm.StringUtils.DataUtils;
import com.jkl.comm.StringUtils.StringUtils;
import com.jkl.dao.drTable.DrTableMapper;
import com.jkl.dao.drTableDetail.DrTableDetailMapper;
import com.jkl.dao.drTemplate.DrTemplateMapper;
import com.jkl.dao.drTemplateDetail.DrTemplateDetailMapper;
import com.jkl.dao.project.PJProjectMapper;
import com.jkl.entity.bsAddition.BsAddition;
import com.jkl.entity.bsWorkflowLog.BsWorkflowLog;
import com.jkl.entity.dept.BSDept;
import com.jkl.entity.drIndex.DrIndex;
import com.jkl.entity.drIndexFormula.DrIndexFormula;
import com.jkl.entity.drTable.DrTable;
import com.jkl.entity.drTableDetail.DrTableDetail;
import com.jkl.entity.drTemplate.DrTemplate;
import com.jkl.entity.drTemplateDetail.DrTemplateDetail;
import com.jkl.entity.param.BSParam;
import com.jkl.entity.person.BsPerson;
import com.jkl.entity.project.po.PJProject;
import com.jkl.service.dept.BSDeptService;
import com.jkl.service.drTable.inter.DrTableServiceInterface;
import com.jkl.service.param.inter.IBSParamService;
import com.jkl.service.person.BsPersonService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class DrTableService implements DrTableServiceInterface {

	@Autowired
	private DrTableMapper DrTableMapper;
	@Autowired
	private DrTableDetailMapper DrTableDetailMapper;
	@Autowired
	private DrTemplateDetailMapper DrTemplateDetailMapper;
	@Autowired
	private DrTemplateMapper DrTemplateMapper;
	@Autowired
	private BsPersonService BsPersonService;
	@Autowired
	private IBSParamService paramService;
	@Autowired
	private BSDeptService BSDeptService;
	@Autowired
	private PJProjectMapper PJProjectMapper;


	// 查询上报主表
	@Override
	public PageInfo<DrTable> drTableById(DrTable drTable) {
		// 查询对应的Level
		// PageHelper.startPage(drTable.getCurrentPage(), drTable.getPageSize());
		String row = drTable.getDeptById();
		List<BSDept> listBSDept = BSDeptService.getDeptObject(row);
		for (int i = 0; i < listBSDept.size(); i++) {

			drTable.setLevel(listBSDept.get(i).getLevel());
			drTable.setDeptCode(String.valueOf(listBSDept.get(i).getRowId()));
			List<DrTable> list = null;
			if (drTable.getLevel() != null && !drTable.getLevel().equals(" ")) {
				PageHelper.startPage(drTable.getCurrentPage(), drTable.getPageSize());
				if (drTable.getLevel() == 1) {
					list = DrTableMapper.drTableById(drTable);
				}
				if (drTable.getLevel() == 2) {
					list = DrTableMapper.drTableByIdLevel(drTable);
				} else if (drTable.getLevel() == 3) {
					list = DrTableMapper.drTableByIdLevelQu(drTable);
				}
				if (list.size() != 0) {
					for (int x = 0; x < list.size(); x++) {
						// 加上 上一级
						if (listBSDept.get(i).getDeptName() != null) {
							if (list.get(x).getBsDept().getParentId() != null) {
								if (list.get(x).getBsDept().getParentId().equals(row)) {
									String name = listBSDept.get(i).getDeptName()
											+ list.get(x).getBsDept().getDeptName();
									list.get(x).setBsDept(list.get(x).getBsDept().setDeptName(name));
								} else {
									String deptRow = list.get(x).getBsDept().getParentId().toString();
									List<BSDept> listBSDeptRow = BSDeptService.getDeptObject(deptRow);
									for (int j = 0; j < listBSDeptRow.size(); j++) {
										if (listBSDeptRow.size() != 0) {
											String name = listBSDeptRow.get(i).getDeptName()
													+ list.get(x).getBsDept().getDeptName();
											list.get(x).setBsDept(list.get(x).getBsDept().setDeptName(name));
										}
									}

								}
							}
						}
						// 把流程状态放进workflow_node
						list.get(x).setWorkflowNode(Integer.parseInt(list.get(x).getWorkflowCode()));

						// level link cycle
						BSParam bSParam = new BSParam();
						bSParam.setGroupCode("data_report_1");

						if (list.get(i).getWorkflowCode() != null) {
							bSParam.setParamCode(list.get(x).getWorkflowCode());
							BSParam bSParamTemp = paramService.queryCode(bSParam);
							if (bSParamTemp != null) {
								list.get(x).setWorkflowCode(bSParamTemp.getValueCode());
							}
						}
					}
				}
				return new PageInfo<>(list);
			}
		}
		return null;
	}

	// 插入上报主表
	@Transactional(rollbackFor = Exception.class)
	@Override
	public String drTablesave(DrTable drTable) {
		DrTemplateDetail drTemplateDetail = new DrTemplateDetail();
		String name = "";
		List<String> tempelName = new ArrayList<String>();
		int z = 0;
		if (drTable.getCheckNode().size() != 0) {
			for (int j = 0; j < drTable.getCheckNode().size(); j++) {
				DrTable DrTables = new DrTable();
				String S = drTable.getCheckNode().get(j).getDeptCode();
				// if(S!=null) {
				int DeptId = 0;
				BsPerson person = new BsPerson();
				DrTemplate drTemplate = new DrTemplate();
				if (drTable.getTemplateId() != null) {
					drTemplate.setRowId(drTable.getTemplateId());
				}
				List<DrTemplate> drtemplateList = DrTemplateMapper.selectTableId(drTemplate);
				if (S != null) {
					DeptId = Integer.parseInt(S);
					person.setDeptId(DeptId);
					if (drtemplateList.size() != 0) {
						for (int b = 0; b < drtemplateList.size(); b++) {
							if (drtemplateList.get(b).getTableLevel().equals("5")) {
								// 查询该机构垃圾运往哪些处置厂
								List<PJProject> unitList = PJProjectMapper.pjProjectUnitListdeptId(DeptId);
								if (unitList.size() != 0 && unitList != null) {
									for (int d = 0; d < unitList.size(); d++) {
										int projectRow = unitList.get(d).getPJProjectUnit().getProjectId();
										// 存对应的处置厂的名称，生成对应的表名
										if (projectRow != 0) {
											PJProject project = PJProjectMapper.PJProjectByrowId(projectRow, null);
											if (project != null) {
												tempelName.add(project.getProjectName());
											}

										}
									}
									DrTables.setDeptId(DeptId);
								} else {
									drTable.setDeptName("没有符合条件的区县--");
									return "0";
								}

							} else {
								DrTables.setDeptId(DeptId);
							}
						}

					}

				} else {
					DeptId = drTable.getCheckNode().get(j).getRowId();
					person.setDeptId(DeptId);
				}
				List<BsPerson> BsPersoTemp = BsPersonService.getPersonByDept(person);
				for (int f = 0; f < BsPersoTemp.size(); f++) {

					DrTables.setPersonId(BsPersoTemp.get(f).getRowId());
				}

				DrTables.setTemplateId(drTable.getTemplateId());

				DrTables.setSequence(drTable.getSequence());
				DrTables.setOperTime(drTable.getOperTime());

				SimpleDateFormat dateStr = new SimpleDateFormat("yyyy-MM-dd");

				if (drTable.getPeriod() == null) {
					if (drtemplateList != null) {
						for (int i = 0; i < drtemplateList.size(); i++) {
							String cycle = drtemplateList.get(i).getTableCycle();
							String Period = null;
							Date data = new Date();
							if (cycle.equals("d")) {
								// "日-"+
								String s = DataUtils.getDayStart();
								Period = s;
							} else if (cycle.equals("w")) {
								// "周-"+
								String s = dateStr.format(DataUtils.getFirstDayOfWeek(data));
								Period = s;
							} else if (cycle.equals("m")) {
								// "月-"+
								Integer y = DataUtils.getNowYear();
								Integer s = DataUtils.getNowMonth();
								String yue = StringUtils.changeNumberforString(Integer.valueOf(s).longValue(), 2);
								Period = y + "-" + yue;
							} else if (cycle.equals("q")) {
								// "季-"+
								Integer y = DataUtils.getNowYear();
								String s = dateStr.format(DataUtils.getFirstSeasonDate(data));
								String yue = StringUtils.changeNumberforString(Integer.valueOf(s).longValue(), 2);
								Period = y + "-" + yue;
							} else if (cycle.equals("y")) {
								// 年-
								Integer s = DataUtils.getNowYear();
								Period = "" + s;
							}
							DrTables.setPeriod(Period);
						}
					}
				} else {
					// 时间不等null
					// 截取日期
					String Period = null;
					if (drtemplateList != null) {
						for (int i = 0; i < drtemplateList.size(); i++) {
							String cycle = drtemplateList.get(i).getTableCycle();
							if (cycle.equals("d")) {
								// "日-"+
								String s = drTable.getPeriod();
								Period = s;
							} else if (cycle.equals("w")) {
								// "周-"+
								String s = null;
								try {
									s = dateStr.format(DataUtils.getFirstDayOfWeek(dateStr.parse(drTable.getPeriod())));
								} catch (ParseException e) {
									e.printStackTrace();
								}
								Period = s;
							} else if (cycle.equals("m")) {
								// "月-"+
								String str = drTable.getPeriod();
								String yue = str.substring(0, drTable.getPeriod().length() - 3);
								Period = yue;
							} else if (cycle.equals("q")) {
								// "季-"+
								String s = null;
								try {
									s = dateStr
											.format(DataUtils.getFirstSeasonDate(dateStr.parse(drTable.getPeriod())));
								} catch (ParseException e) {
									e.printStackTrace();
								}
								Period = s;
							} else if (cycle.equals("y")) {
								// 年-
								String str = drTable.getPeriod();
								String yue = str.substring(0, drTable.getPeriod().length() - 6);
								Period = yue;
							}
						}
					}
					DrTables.setPeriod(Period);

				}
				List<DrTable> drTablesList = DrTableMapper.drTableList(DrTables);
				DrTables.setWorkflowCode("11");
				DrTables.setStatus("1");
				if (tempelName.size() != 0 && tempelName != null) {
					for (int k = 0; k < tempelName.size(); k++) {
						DrTable DrTableTemp = new DrTable();

						if (drTablesList.size() == 0) {
							DrTables.setTemplateName((tempelName.get(k) + "---" + drTable.getTemplateName()));
							DrTableTemp.setDeptId(DrTables.getDeptId());
							DrTableTemp.setOperTime(DrTables.getOperTime());
							DrTableTemp.setPeriod(DrTables.getPeriod());
							DrTableTemp.setPersonId(DrTables.getPersonId());
							DrTableTemp.setSequence(DrTables.getSequence());
							DrTableTemp.setStatus(DrTables.getStatus());
							DrTableTemp.setTemplateId(DrTables.getTemplateId());
							DrTableTemp.setTemplateName(DrTables.getTemplateName());
							DrTableTemp.setWorkflowCode(DrTables.getWorkflowCode());
							DrTableTemp.setWorkflowNode(DrTables.getWorkflowNode());
							z = DrTableMapper.insert(DrTableTemp);
						} else {
							for (int i = 0; i < drTablesList.size(); i++) {
								name += drTablesList.get(i).getBsDept().getDeptName() + ',';
							}
							drTable.setDeptName(name.substring(0, name.length() - 1));
						}
						if (z != 0) {
							drTemplateDetail.setTableId(DrTables.getTemplateId());
							List<DrTemplateDetail> list = DrTemplateDetailMapper.selectDetailById(drTemplateDetail);
							for (int t = 0; t < list.size(); t++) {
								DrTableDetail drTableDetail = new DrTableDetail();
								drTableDetail.setTableId(DrTableTemp.getRowId());
								drTableDetail.setIndexCode(list.get(t).getIndexCode());
								drTableDetail.setIndexName(list.get(t).getIndexName());
								drTableDetail.setSequence(list.get(t).getSequence());
								drTableDetail.setValue("");
								if (list.get(t).getDrIndex() != null) {
									drTableDetail.setUnit(list.get(t).getDrIndex().getUnit());
								}
								drTableDetail.setStatus("1");
								DrTableDetailMapper.insert(drTableDetail);
							}
						}

					}

				} else {
					DrTables.setTemplateName(drTable.getTemplateName());
					if (drTablesList.size() == 0) {
						z = DrTableMapper.insert(DrTables);
						/*
						 * 添加成功的机构名称 List<BSDept> deptRow=
						 * BSDeptService.getDeptObject(DrTables.getDeptById()); if(deptRow.size()!=0){
						 * for (int i=0; i<deptRow.size();i++) name+=deptRow.get(i).getDeptName()+','; }
						 */

					} else {
						for (int i = 0; i < drTablesList.size(); i++) {
							name += drTablesList.get(i).getBsDept().getDeptName() + ',';
						}
						drTable.setDeptName(name.substring(0, name.length() - 1));
					}
				}
				// drTableTemp.add(DrTables);
				// 判断表是否已经生成

				// 插入drTableDetail
				if (z != 0) {
					drTemplateDetail.setTableId(DrTables.getTemplateId());
					List<DrTemplateDetail> list = DrTemplateDetailMapper.selectDetailById(drTemplateDetail);
					for (int t = 0; t < list.size(); t++) {
						DrTableDetail drTableDetail = new DrTableDetail();
						drTableDetail.setTableId(DrTables.getRowId());
						drTableDetail.setIndexCode(list.get(t).getIndexCode());
						drTableDetail.setIndexName(list.get(t).getIndexName());
						drTableDetail.setSequence(list.get(t).getSequence());
						drTableDetail.setValue("");
						if (list.get(t).getDrIndex() != null) {
							drTableDetail.setUnit(list.get(t).getDrIndex().getUnit());
						}
						drTableDetail.setStatus("1");
						DrTableDetailMapper.insert(drTableDetail);
					}
				}
				// }
			}
		} else {
			// r如果机构id为null
			DrTemplate drTemplate = new DrTemplate();
			SimpleDateFormat dateStr = new SimpleDateFormat("yyyy-MM-dd");
			if (drTable.getTemplateId() != null) {
				drTemplate.setRowId(drTable.getTemplateId());
			}
			List<DrTemplate> drtemplateList = DrTemplateMapper.selectTableId(drTemplate);
			if (drtemplateList != null) {
				for (int i = 0; i < drtemplateList.size(); i++) {
					String cycle = drtemplateList.get(i).getTableCycle();
					String Period = null;
					Date data = new Date();
					if (cycle.equals("d")) {
						// "日-"+
						String s = DataUtils.getDayStart();
						Period = s;
					} else if (cycle.equals("w")) {
						// "周-"+
						String s = dateStr.format(DataUtils.getFirstDayOfWeek(data));
						Period = s;
					} else if (cycle.equals("m")) {
						// "月-"+
						Integer s = DataUtils.getNowMonth();
						Period = "" + s;
					} else if (cycle.equals("q")) {
						// "季-"+
						String s = dateStr.format(DataUtils.getFirstSeasonDate(data));
						Period = s;
					} else if (cycle.equals("y")) {
						// 年-
						Integer s = DataUtils.getNowYear();
						Period = "" + s;
					}
					drTable.setPeriod(Period);
				}
			}
			drTable.setWorkflowCode("11");
			drTable.setStatus("1");
			z = DrTableMapper.insert(drTable);
			if (z != 0) {
				drTemplateDetail.setTableId(drTable.getTemplateId());
				List<DrTemplateDetail> list = DrTemplateDetailMapper.selectDetailById(drTemplateDetail);
				for (int j = 0; j < list.size(); j++) {
					DrTableDetail drTableDetail = new DrTableDetail();
					drTableDetail.setTableId(drTable.getRowId());
					drTableDetail.setIndexCode(list.get(j).getIndexCode());
					drTableDetail.setIndexName(list.get(j).getIndexName());
					drTableDetail.setSequence(list.get(j).getSequence());
					drTableDetail.setValue("");
					if (list.get(j).getDrIndex() != null) {
						drTableDetail.setUnit(list.get(j).getDrIndex().getUnit());
					}
					drTableDetail.setStatus("1");
					DrTableDetailMapper.insert(drTableDetail);
				}

			}
		}
		/*
		 * if(name.equals("")) { String x=String.valueOf(z); return x; }else {
		 */
		// 将插入成功的和不成功的机构名称返回
		String x = String.valueOf(z);
		return x;
	}

	// 生成表查询
	@Override
	public PageInfo<DrTable> drTableList(DrTable drTable) {
		String row = drTable.getDeptById();
		List<BSDept> listBSDept = BSDeptService.getDeptObject(row);
		for (int i = 0; i < listBSDept.size(); i++) {

			drTable.setLevel(listBSDept.get(i).getLevel());
			drTable.setDeptCode(String.valueOf(listBSDept.get(i).getRowId()));
			List<DrTable> list = null;
			if (drTable.getLevel() != null && !drTable.getLevel().equals(" ")) {
				PageHelper.startPage(drTable.getCurrentPage(), drTable.getPageSize());
				if (drTable.getLevel() == 1) {
					list = DrTableMapper.drTableListId(drTable);
				}
				if (drTable.getLevel() == 2) {
					list = DrTableMapper.drTableListIdLevel(drTable);
				} else if (drTable.getLevel() == 3) {
					list = DrTableMapper.drTableListIdLevelQu(drTable);
				}
				if (list.size() != 0) {
					for (int x = 0; x < list.size(); x++) {
						// 加上 上一级
						if (listBSDept.get(i).getDeptName() != null) {
							if (list.get(x).getBsDept().getParentId() != null) {
								if (list.get(x).getBsDept().getParentId().equals(row)) {
									String name = listBSDept.get(i).getDeptName()
											+ list.get(x).getBsDept().getDeptName();
									list.get(x).setBsDept(list.get(x).getBsDept().setDeptName(name));
								} else {
									String deptRow = list.get(x).getBsDept().getParentId().toString();
									List<BSDept> listBSDeptRow = BSDeptService.getDeptObject(deptRow);
									for (int j = 0; j < listBSDeptRow.size(); j++) {
										if (listBSDeptRow.size() != 0) {
											String name = listBSDeptRow.get(i).getDeptName()
													+ list.get(x).getBsDept().getDeptName();
											list.get(x).setBsDept(list.get(x).getBsDept().setDeptName(name));
										}
									}

								}
							}
						}
						// 把流程状态放进workflow_node
						list.get(x).setWorkflowNode(Integer.parseInt(list.get(x).getWorkflowCode()));

						// level link cycle
						BSParam bSParam = new BSParam();
						bSParam.setGroupCode("data_report_1");

						if (list.get(i).getWorkflowCode() != null) {
							bSParam.setParamCode(list.get(x).getWorkflowCode());
							BSParam bSParamTemp = paramService.queryCode(bSParam);
							if (bSParamTemp != null) {
								list.get(x).setWorkflowCode(bSParamTemp.getValueCode());
							}
						}
					}
				}
				return new PageInfo<>(list);
			}
		}
		return null;
	}

	// 修改
	@Override
	public int updateDrTable(DrTable drTable) {
		int z = DrTableMapper.updateByPrimaryKey(drTable);
		if (z != 0) {
			return z;
		} else {
			return 0;
		}
	}

	@Override
	public int deleteDrTable(DrTable drTable) {
		int z = DrTableMapper.delete(drTable);
		if (z != 0) {
			return z;
		} else {
			return 0;
		}
	}

	// 修改状态
	@Override
	public int updateWorkflowCode(DrTable drTable) {
		int z = DrTableMapper.updateWorkflowCode(drTable);
		if (z != 0) {
			return z;
		} else {
			return 0;
		}
	}

	// 修改是否启用
	@Override
	public int updateStatus(DrTable drTable) {
		drTable.setStatus("0");
		int z = DrTableMapper.updateStatus(drTable);
		if (z != 0) {
			return z;
		} else {
			return 0;
		}
	}

	@Override
	public int deleteTable(int param) {
		int a=DrTableMapper.deleteTable(param);
		int b=DrTableMapper.deleteTableDetail(param);
		DrTableMapper.deleteTableLog(param);
		if(a==1&&b!=0) {
			return 1;
		}else {
			return 0;
		}
	}
	@Override
	public int addTable(DrTable drTable) {
		return DrTableMapper.addDrTable(drTable);
	}
	@Override
	public int addTableDetail(DrTableDetail tabledeta) {
		return DrTableMapper.addTableDetail(tabledeta);
	}  
    
	@Override
	public DrTemplate queryTemplate(int id) {
		return DrTableMapper.queryTemplate(id);
	}  
	@Override
	public int addTemplate(DrTemplate template) {
		return DrTableMapper.addTemplate(template);
	}  
	@Override
	public int setTemplateDetailStatus(int id) {
		return DrTableMapper.setTemplateDetailStatus(id);
	}  
	@Override
	public void addTemplateDetails(List<DrTemplateDetail> templateDetails) {
		for(DrTemplateDetail temdet:templateDetails) {
			DrTableMapper.addTemplateDetail(temdet);
		}
	} 
	@Override
	public DrTemplateDetail queryTemplateDetail(int tableId,String indexCode) {
		return DrTableMapper.queryTemplateDetail(tableId,indexCode);
	} 
	@Override
	public void addTemplateDetail(DrTemplateDetail addTemplateDetail) {
		 DrTableMapper.addTemplateDetail(addTemplateDetail);
	} 
	@Override
	public int setTemplateDetailStatus2(int id) {
		return DrTableMapper.setTemplateDetailStatus2(id);
	}  
	@Override
	public DrIndex queryIndex(int id) {
		return DrTableMapper.queryIndex(id);
	} 
	@Override
	public int addIndex(DrIndex index) {
		 return DrTableMapper.addIndex(index);
	} 
	@Override
	public int updateIndex(DrIndex index) {
		return DrTableMapper.updateIndex(index);
	}  
	@Override
	public DrIndexFormula queryIndexFormula(int id) {
		return DrTableMapper.queryIndexFormula(id);
	} 
	@Override
	public int addIndexFormula(DrIndexFormula indexformu) {
		 return DrTableMapper.addIndexFormula(indexformu);
	} 
	@Override
	public int updateIndexFormula(DrIndexFormula indexformu) {
		return DrTableMapper.updateIndexFormula(indexformu);
	}  
	@Override
	public BsWorkflowLog[] queryworkflowLogs(int id) {
		return DrTableMapper.queryworkflowLogs(id);
	}  
	@Override
	public BsAddition queryBsAddition(int id) {
		return DrTableMapper.queryBsAddition(id);
	}  
	@Override
	public DrTableDetail[] queryTableDetails(int id) {
		return DrTableMapper.queryTableDetails(id);
	}  
	@Override
	public DrTable queryTable(int id) {
		return DrTableMapper.queryTable(id);
	}  
	@Override
	public int updateTable(DrTable table) {
		return DrTableMapper.updateTable(table);
	}  
	@Override
	public DrTableDetail queryTableDetail(int id) {
		return DrTableMapper.queryTableDetail(id);
	}  
	@Override
	public int addBsWorkflowLog(BsWorkflowLog bsWorkflowLog) {
		return DrTableMapper.addBsWorkflowLog(bsWorkflowLog);
	}  
	@Override
	public int updateTableLog(int id) {
		return DrTableMapper.updateTableLog(id);
	}  
}
